using System;
using System.Linq;
using Pay.DTO;
using System.Collections.Generic;
using Pay.Data;
using Pay.Service.Cache;
using Pay.Core;
using Pay.IService;
using Pay.TO;
using System.Linq.Expressions;

namespace Pay.Service {
    public class PaymentService : ServiceBase, IPaymentService, IDisposable {
        private IUnitOfWork _iUnitOfWork;

        public PaymentService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
        }

        public payment_dto Get(long id) {
            if (id == 0)
                return null;
            return context.Payments.Where(c => c.Id == id).FromCacheFirstOrDefault<Payment, payment_dto>("Payment");
        }

        public IEnumerable<payment_dto> Get() {
            return context.Payments.FromCache<Payment, payment_dto>("Payment");
        }

        /// <summary>
        /// 新增支付方式
        /// </summary>
        /// <param name="dto"></param>
        public int Add(payment_dto dto) {
            if (context.Payments.Exist(c => c.Channel == dto.channel))
                throw new ServerErrorException("用户已经是支付方式");

            Payment model = new Payment();
            dto.ToDtoObject(model);
            context.Payments.Add(model);
            int result = _iUnitOfWork.Commit("Payment", "Merchant");
            dto.id = model.Id;
            return result;
        }

        /// <summary>
        /// 更新支付方式
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public int Update(payment_dto dto) {
            var model = context.Payments.FindById(dto.id);
            dto.ToDtoObject<Payment>(model);
            int result = _iUnitOfWork.Commit("Payment", "Merchant");
            return result;
        }

        /// <summary>
        /// 删除支付方式
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Delete(long id) {
            var model = context.Payments.FindById(id);
            context.MerchantPayments.Remove(cw => cw.PaymentId == id);
            context.Payments.Remove(model);
            int result = _iUnitOfWork.Commit("Payment", "Merchant");
            return result;
        }
    }
}
